package com.ngo.utils;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author yang.yang@karakal.com.cn
 * @version V1.0
 * @Description: 公用工具
 * @date 2017-10-03 15:22
 */
public class CommomUtils {

    /**
     * 按字母顺序链接成请求参数 a=1&b=2
     * @param map
     * @return
     */
    public static String concatRequestParams(Map<String, String> map) {
        if (map == null) {
            return null;
        }
        Map<String, String> treeMap = null;
        if (map instanceof TreeMap) {
            treeMap = map;
        } else {
            treeMap = new TreeMap<String, String>(map);
        }
        StringBuilder sf = new StringBuilder(256);
        int i = 0;
        for (String key : treeMap.keySet()) {
            i ++;
            sf.append(key + "=" + getStringVal(treeMap.get(key), true));
            if (i < treeMap.size()) {
                sf.append("&");
            }
        }
        return sf.toString();
    }

    /**
     * 返回字符串值，如果参数为null，指定returnEmpty为true，则返回空字符串，否则返回null
     * @param obj
     * @return
     */
    public static String getStringVal(Object obj, boolean returnEmpty) {
        if (null == obj) {
            return returnEmpty ? "" : null;
        }
        try {
            return obj.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static Long getTimeByHourLater(int hour) {

        Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + hour);

        return calendar.getTimeInMillis();
    }

    public static void main(String[] args) {
        Map<String,String> redirectParams = new HashMap<>();
        redirectParams.put("userid","1");
        redirectParams.put("name","2");
        redirectParams.put("department","2");
        redirectParams.put("position","3");
        redirectParams.put("mobile","2");
        redirectParams.put("gender","2");
        String requestParams = CommomUtils.concatRequestParams(redirectParams);
        System.out.println(requestParams);
    }
}
